package com.yc.thread.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 使用BlockingQueue实现生产者消费者
 */
public class ConsumerProducer {
    public static final String EXIT_MSG = "good bye";

    public static void main(String[] args) {
        // 给定capacity
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);
        new Thread(producer).start();
        new Thread(consumer).start();
    }

    /**
     * 生产者类
     */
    static class Producer implements Runnable {

        private BlockingQueue<String> queue;

        public Producer(BlockingQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            for (int i=0; i<10; i++) {
                try {
                    Thread.sleep(1000L);
                    String msg = "Message " + i;
                    System.out.println("生产了：" + msg);
                    queue.put(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            try {
                System.out.println("生产者停止生产！！");
                queue.put(EXIT_MSG);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 消费者
 */
    static class Consumer implements Runnable {
        private BlockingQueue<String> queue;
        public Consumer(BlockingQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                String msg ;
                while (!EXIT_MSG.equalsIgnoreCase( (msg = queue.take() ))) {
                    System.out.println("消费了：" + msg);
                    Thread.sleep(2000L);
                }

                System.out.println("消费者不能消费");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
